package com.fsq.portscan;

import java.util.LinkedList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;

import com.fsq.portscan.model.Row;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.TableView;
import javafx.scene.control.TreeItem;

public class ScanTaskDefault extends Task<String> implements ScanTask{

	private LinkedList<String> ips;
	private LinkedList<Integer> ports;
	private TreeItem<String> treeItem;
	private ExecutorService threadPool;
	private boolean isStop = false;
	private Integer threadCount;
	private TableView<Row> tableView;
	private Integer to;
	private Label id_status;
	private CheckBox id_autodeleteempty;

	public boolean isStop() {
		return isStop;
	}

	@Override
	public void setStop(boolean isStop) {
		this.isStop = isStop;
	}

	public ScanTaskDefault(LinkedList<String> ips, LinkedList<Integer> ports, TreeItem<String> treeItem,
						   ExecutorService threadPool, Integer threadCount, TableView<Row> tableView, Integer to, Label id_status,
						   CheckBox id_autodeleteempty) {
		super();
		this.ips = ips;
		this.ports = ports;
		this.treeItem = treeItem;
		this.threadPool = threadPool;
		this.threadCount = threadCount;
		this.tableView = tableView;
		this.to = to;
		this.id_status = id_status;
		this.id_autodeleteempty = id_autodeleteempty;
	}

	@Override
	protected String call() throws Exception {
		// TODO Auto-generated method stub

		for (String string : ips) {
			TreeItem<String> treeitemIp = new TreeItem<String>(string);

			if (!id_autodeleteempty.isSelected()) {

				Platform.runLater(new Runnable() {
					@Override
					public void run() {
						treeItem.getChildren().add(treeitemIp);
					}
				});

			}

			for (Integer port : ports) {

				if (isStop) {
					FXMLDocumentController.taskCount--;
					return null;
				}
				ThreadPoolExecutor tpf = (ThreadPoolExecutor) threadPool;
				Integer count = tpf.getQueue().size();
				if (count > 10000) {
					Thread.sleep(2000);
				}
				// System.out.println(count);
				threadPool.execute(new ScanThread(treeitemIp, port, tableView.getItems(), to, id_status, treeItem));
			}
		}
		Thread.sleep(3000);
		FXMLDocumentController.taskCount--;
		return null;
	}

}
